/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.lvyh.lightframe.job.admin.util;

import com.lvyh.lightframe.job.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;

public class FileUtils {
    private static Logger logger = LoggerFactory.getLogger(FileUtils.class);

    public final static String serverConfigDataDir = NetworkUtils.isUnixOS() ? Constants.DEFAULT_DISK_STORE_DIR : System.getProperty("user.home") + Constants.DEFAULT_DISK_STORE_DIR;


    private static void changeFilePermission(File file) {
        // The file permission is set to 600
        file.setExecutable(false, false);
        file.setWritable(false, false);
        file.setReadable(false, false);
        file.setExecutable(false, true);
        file.setWritable(true, true);
        file.setReadable(true, true);
    }

    private static File createTempFile(String name) throws IOException {
        return File.createTempFile(name, ".tmp");
    }

    private static File createFileIfNessary(String filePath) throws IOException {
        final File file = new File(filePath);
        if (!file.exists()) {
            file.createNewFile();
            changeFilePermission(file);// set files permissions
        }
        return file;
    }

    private static void createDirIfNessary(String path) {
        final File dir = new File(path);
        if (dir.isFile()) {
            throw new RuntimeException("path is a file: " + path);
        }
        if (!dir.exists()) {
            if (!dir.mkdirs()) {
                throw new RuntimeException("file directory create failed. Path : " + path);
            } else {
                logger.info("file directory created -> {}", path);
            }
        }
    }


}
